package subraSoft.centaurus.model.report;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.swing.table.TableModel;

import org.apache.log4j.Logger;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;

import subraSoft.centaurus.model.util.CenConfigurationUtil;

public class CenExcel 
{
	private static Logger logger = Logger.getLogger(CenExcel.class);
	
	public static void export2Excel(TableModel model, int[] indices, File file, String pageName) throws IOException
	{
		//int rowCount = model.getRowCount();
		int columnCount = model.getColumnCount();
		
		HSSFWorkbook wb = new HSSFWorkbook();
		HSSFSheet sheet = wb.createSheet(pageName);
		
		HSSFRow rowhead = sheet.createRow((short)0);
		for (int i = 0; i < columnCount; i++) {
			rowhead.createCell((short) i).setCellValue(new HSSFRichTextString(model.getColumnName(i)));
		}
		
		int newIndex = 1;
		for (int selectedIndex : indices) 
		{
			HSSFRow row = sheet.createRow((short)(newIndex++));
			for (int columnIndex = 0; columnIndex < columnCount; columnIndex++) 
			{
				Object valor = model.getValueAt(selectedIndex, columnIndex);
				if( valor != null)
					row.createCell((short)columnIndex).setCellValue(new HSSFRichTextString(valor.toString()));
			}
		}
		
		FileOutputStream fileOut = new FileOutputStream(file);
		wb.write(fileOut);
		fileOut.close();
	}

	public static File generarExcel(TableModel model, int[] indices, String fileName) throws CenReportException
	{
		File file = null;
		try 
		{
			long milis = System.currentTimeMillis();
			String tempFile = CenConfigurationUtil.getInstance().getTempFolder()+File.separator+fileName+"-"+milis+".xls";
			file = new File(tempFile);
			export2Excel(model, indices, file, fileName);
		} 
		catch (Exception e) 
		{
			logger.error(e, e);
			throw new CenReportException("No se pudo generar el reporte ", e);
		}
		return file;
	}
}
